package com.zzsoft.nettysocket;/**
 * Created by zhanghb on 2019/9/2.
 */

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;
import com.zzsoft.util.SocketUtil;
import org.springframework.util.StringUtils;

import java.util.logging.Handler;

/**
 * @Description
 * @Author Zhanghb
 * @Date
 */
@Slf4j
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接激活");
        log.info("实例名称1："+ctx.name());
        // 若没有StringEncoder，则发送不出去字符串。
        ctx.writeAndFlush("hello,world! 你好,世界!");
       log.info("写入完成");
        /*SocketUtil.add("001",(SocketChannel)ctx.channel());
        log.info("缓存channel"+SocketUtil.get("001"));*/
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("实例名称2："+ctx.name());
        log.info("从客户端读取数据："+msg);
       if(msg!=null&&!StringUtils.isEmpty(msg.toString())){
           String key=msg.toString();
           if(key.contains("key")){
               if(SocketUtil.get(key)==null){
                   SocketUtil.add(key,(SocketChannel)ctx.channel());
                   log.info("缓存channel到key："+key);
               }
           }
       }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.warn( "发生错误，关闭链接。", cause);
        SocketUtil.remove((SocketChannel)ctx.channel());
        ctx.close();
    }
}

